package commands;

import user.Admin;
import user.User;
import messages.*;
import core.UserManager;
import event.*;


/**
 * The AccountRemove command.
 * 
 * This command will handle AccountRemove messages.
 */
public class AccountRemoveCommand extends Command {

	
	public AccountRemoveCommand(Message message, User user) {
		super(message, user);
	}
	
	
	@Override
	public void execute() {
		UserManager userManager = controller.getUserManager();
		AccountRemoveMessage message = (AccountRemoveMessage) this.message;
		message.setSenderLogin(this.user.getLogin());
		
		String login = message.getLogin();
		
		synchronized(userManager) {
			AccountRemotionFailedMessage.ErrorCode errorCode = null;
			
			if (!(this.user instanceof Admin))
				errorCode = AccountRemotionFailedMessage.ErrorCode.InsufficientPermissions;
			
			else if (login == null || login == "")
				errorCode = AccountRemotionFailedMessage.ErrorCode.InvalidParameters;
				
			else if (userManager.isLoginAvailable(login))
				errorCode = AccountRemotionFailedMessage.ErrorCode.UnknownUser;
			
			if (errorCode != null) {
				controller.fireAccountRemotionFailedEvent(new AccountRemotionFailedEventArgs(
						this.user.getLogin(), new AccountRemotionFailedMessage(message, errorCode)));
				
				return;
			}
			
			if (userManager.isLoggedIn(login)) {
				Command command = new QuitCommand(new QuitMessage(), userManager.getUser(login));
				command.execute();
			}
			
			userManager.removeUser(login);
		}
		
		controller.fireAccountRemotionSuccessful(new AccountRemotionSuccessfulEventArgs(
				this.user.getLogin(), new AccountRemotionSuccessfulMessage(this.user.getLogin(), login)));
	}
}
